package ipproxy.database;

import static java.lang.System.out;

import java.util.ArrayList;
import java.util.List;

import ipproxy.IPModel.IPMessage;
import ipproxy.IPModel.SerializeUtil;
import redis.clients.jedis.Jedis;

/**
 * Created by hg_yi on 17-8-9.
 */
public class MyRedis {
    Jedis jedis = RedisDB.getJedis();

    //将ip信息保存在Redis列表中
    public void setIPToList(List<IPMessage> ipMessages) {
        for (IPMessage ipMessage : ipMessages) {
            //首先将ipMessage进行序列化
            byte[] bytes = SerializeUtil.serialize(ipMessage);

            jedis.rpush("IPPool".getBytes(), bytes);
        }
    }

    //将Redis中保存的对象进行反序列化
    public List<IPMessage> getIPByList(String key) {
        Long length = jedis.llen(key);
        List<byte[]> list= jedis.lrange("IPPool".getBytes(), 0,length);
        List<IPMessage> list2=new ArrayList<>();
        for(int i=0;i<length;i++){
        	Object o = SerializeUtil.unserialize(list.get(i));
        	if (o instanceof IPMessage) {
        		list2.add((IPMessage)o);
            } else {
                out.println("不是IPMessage的一个实例~");
                return null;
            }
        	
        }
        return list2;
        
    }

    public void deleteKey(String key) {
        jedis.del(key);
    }

    public void close() {
        RedisDB.close(jedis);
    }
}
